
/*
 * Copyright (C) 2008-2009 Archie L. Cobbs. All rights reserved.
 *
 * $Id: XMLDatabase.java 377 2010-03-11 20:50:18Z archie.cobbs $
 */

package org.dellroad.sidekar.xml;

import org.dellroad.sidekar.Database;
import org.dellroad.sidekar.schema.model.SchemaModel;
import org.jibx.runtime.IUnmarshallingContext;

/**
 * Class associated with &lt;sidekar-database&gt; in the JiBX binding context.
 */
class XMLDatabase {

    private XMLImporter xmlImporter;
    private Database db;
    private boolean createDatabase;

    private SchemaModel schemaModel;

    @SuppressWarnings("unused")
    private XMLData data;

    // Used during marshalling
    public XMLDatabase(Database db, String name, boolean nodata) {
        this.db = db;
        this.schemaModel = db.getSchemaModel();
        if (!nodata)
            this.data = new XMLData(this);
    }

    // Used during unmarshalling
    public XMLDatabase(XMLImporter xmlImporter) {
        if (xmlImporter == null)
            throw new IllegalArgumentException("null xmlImporter");
        this.xmlImporter = xmlImporter;
        this.db = xmlImporter.getDatabase();
        this.createDatabase = this.db == null;
    }

    public Database getDatabase() {
        return this.db;
    }

    public SchemaModel getSchemaModel() {
        return this.schemaModel;
    }

    // During unmarshalling, when we have parsed the schema we are ready to create the database
    public void setSchemaModel(SchemaModel schemaModel) {

        // Sanity check
        if (!this.createDatabase)
            throw new IllegalStateException("this import allows data only");

        // Validate it
        schemaModel.validate();

        // Save it
        this.schemaModel = schemaModel;

        // Open database
        assert this.db == null;
        this.db = new Database(this.schemaModel);
        this.db.open();
    }

    public void finish() {
        if (this.createDatabase)
            this.db.close();
    }

    /**
     * Factory method used during unmarshalling.
     */
    public static XMLDatabase newInstance(IUnmarshallingContext ctx) {
        return new XMLDatabase((XMLImporter)ctx.getUserContext());
    }
}

